package com.java1412.filter;

import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;

/**
 * @author java1412
 * @since 2023-07-20 15:50:08
 */
@Component
public class MyFilter extends ZuulFilter {
    @Override
    public String filterType() {
        return "pre";
    }

    @Override
    public int filterOrder() {
        return 0;
    }

    @Override
    public boolean shouldFilter() {
        return true;
    }

    @Override
    public Object run() throws ZuulException {
        // 获取请求上下文
        RequestContext context = RequestContext.getCurrentContext();
        // 从上下文对象中获取request
        HttpServletRequest request = context.getRequest();
        System.out.println(request.getMethod() + " : " + request.getRequestURL().toString());
        // 获取令牌
        String accessToken = request.getParameter("token");
        // 判断令牌
        if (accessToken == null) {
            // 向页面返回信息
            System.out.println("token是空的");
            context.setSendZuulResponse(false);
            context.setResponseStatusCode(401);
            // 将提示信息响应给页面
            try {
                context.getResponse().getWriter().write("token is empty");
            } catch (Exception e) {
                e.printStackTrace();
            }
            return null;
        }
        System.out.println("token不是空的");
        return context;
    }
}
